import tkinter as tk
import json
import re
from tabulate import tabulate
from tkinter import filedialog
from pathlib import Path


def kind(what):
    what = str(type(what))[8:-2]
    if what == 'str':
        return '字符串'
    elif what == 'float':
        return '小数'
    elif what == 'int':
        return '整数'
    elif what == 'bool':
        return '逻辑'
    else:
        return '未知'


Chinese = {
    'Button_active_bg': '按钮按下时背景',
    'Button_active_fg': '按钮按下时字体颜色',
    'Button_bg': '括号按钮背景',
    'Button_bg_fun': '功能按钮背景',
    'Button_bg_notice': '警示性按钮背景',
    'Button_bg_num': '数字按键背景',
    'autosize': '是否由程序自动调整大小，否则根据height和width参数锁定大小',
    'fg': '程序背景',
    'height': '窗口高度',
    'width': '窗口宽度',
    'topmost': '窗口是否始终置顶',
    'fontsize': '软件内字体大小',
}

root = tk.Tk()
root.withdraw()

path = filedialog.askopenfilename(title='选择一个你要进行编辑的settings.json文件',
                                  filetypes=[('JSON文件', '.json')])
root.destroy()

print('你选择的文件路径为{}'.format(path))
print('正在对该文件进行读取...')
path = Path(path)
contents = path.read_text()
dictionary = json.loads(contents)
if not isinstance(dictionary, dict):
    print('\n你所选取的文件内容不是一个字典，请确保该文件所属的程序是与该软件同一个开发者开发的')
    input('程序已停止运行，按Enter以退出……')
    exit()
print('\n读取成功')
print('该文件涵盖以下自定义项目：')
a = []
for i in dictionary.keys():
    a.append(
        [i, kind(dictionary[i]), Chinese[i] if i in Chinese else '(暂无汉语翻译)'])
print(tabulate(a, headers=['名称', '值类型', '汉语翻译'], tablefmt='fancy_grid'))
a = []

run = True
print('\n该程序以命令的模式进行使用，以下是命令列表：')
print(
    tabulate([['read', '显示字典键对应的值的内容，需在后面指定键名'],
              ['write', '对指定的键值进行修改，需在后面指定键名'], ['save', '保存已有的修改'],
              ['exit', '退出程序'], ['sa-ex', '保存并退出'], ['print', '显示该字典的所有键值对']],
             headers=['命令', '介绍'],
             tablefmt='fancy_grid'))
while run:
    code = input('>>> ')
    if re.match(r'^read', code):
        if code[5:] in dictionary:
            print('{}的内容是{}'.format(code[5:], dictionary[code[5:]]))
        elif code[5:] == '':
            print('你没有指定哪个键')
        else:
            print('你输入的名字不在字典里，请检查你的输入')
    elif re.match(r'^write', code):
        if code[6:] in dictionary:
            print('{}的内容是{}'.format(code[6:], dictionary[code[6:]]))
            print('{}的文本类型是{}'.format(code[6:], kind(dictionary[code[6:]])))
            try:
                what = input('请告诉我你要把它改成什么: ')
                if kind(dictionary[code[6:]]) == '字符串':
                    dictionary[code[6:]] = what
                elif kind(dictionary[code[6:]]) == '小数':
                    dictionary[code[6:]] == float(what)
                elif kind(dictionary[code[6:]]) == '整数':
                    dictionary[code[6:]] == int(what)
                elif kind(dictionary[code[6:]]) == '逻辑':
                    dictionary[code[6:]] == bool(what)
                else:
                    print('由于你所选择的键值类型未知，无法进行修改')
            except ValueError:
                print('你输入的值不是一个{}，无法对这个值进行修改'.format(
                    kind(dictionary[code[6:]])))
        elif code[6:] == '':
            print('你没有指定哪个键')
    elif re.match(r'^save', code):
        contents = json.dumps(dictionary,
                              sort_keys=True,
                              indent=4,
                              separators=(',', ':'))
        print('准备保存……')
        path.write_text(contents)
        print('保存成功')
    elif re.match(r'^exit', code):
        run = False
    elif re.match(r'^sa-ex', code):
        contents = json.dumps(dictionary,
                              sort_keys=True,
                              indent=4,
                              separators=(',', ':'))
        print('准备保存……')
        path.write_text(contents)
        print('保存成功')
        run = False
    elif re.match(r'^print', code):
        a = []
        for i in dictionary.keys():
            a.append([i, dictionary[i], kind(dictionary[i])])
        print(tabulate(a, headers=['键', '值', '类型'], tablefmt='orgtbl'))
input('按Enter以退出')
